<template>
  <div class="add-subitem-container">

    <!-- 主内容区 -->
    <main class="main-content">
      <div class="add-subitem-wrapper">
        <h2 class="page-title">添加课程任务项</h2>
        
        <!-- 课程信息显示 -->
        <div v-if="courseInfo" class="course-info-card">
          <el-card>
            <div slot="header" class="card-header">
              <span>当前课程信息</span>
            </div>
            <div class="course-info-content">
              <p><strong>课程名称：</strong>{{ courseInfo.title }}</p>
              <p><strong>授课教师：</strong>{{ courseInfo.teacher }}</p>
              <p><strong>上课时间：</strong>{{ formatDate(courseInfo.courseTime) }}</p>
            </div>
          </el-card>
        </div>
        
        <!-- 添加任务项表单 -->
        <el-form ref="subitemForm" :model="subitemForm" :rules="subitemRules" label-width="120px" class="subitem-form">
          <el-form-item label="任务名称" prop="title">
            <el-input v-model="subitemForm.title" placeholder="请输入任务名称" maxlength="50"></el-input>
          </el-form-item>
          
          <el-form-item label="任务类型" prop="type">
            <el-select v-model="subitemForm.type" placeholder="请选择任务类型">
              <el-option label="作业" value="作业"></el-option>
              <el-option label="测验" value="测验"></el-option>
              <el-option label="讨论" value="讨论"></el-option>
              <el-option label="阅读" value="阅读"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="截止时间" prop="deadline">
            <el-date-picker
              v-model="subitemForm.deadline"
              type="datetime"
              placeholder="选择日期时间"
              format="yyyy-MM-dd HH:mm"
              value-format="timestamp"
              style="width: 100%;"
            ></el-date-picker>
          </el-form-item>
          
          <el-form-item label="任务描述" prop="description">
            <el-input v-model="subitemForm.description" type="textarea" placeholder="请输入任务描述" :rows="6" maxlength="1000"></el-input>
          </el-form-item>
          
          <el-form-item label="任务附件">
            <el-upload
              class="upload-demo"
              ref="upload"
              :action="uploadUrl"
              :headers="{ 'Authorization': `Bearer ${token}` }"
              :on-success="handleFileUpload"
              :on-remove="handleRemove"
              multiple
              :show-file-list="true"
              :file-list="fileList"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过2MB
              </div>
            </el-upload>
          </el-form-item>
          
          <!-- 提交按钮 -->
          <el-form-item>
            <el-button type="primary" @click="handleAddSubitem" :loading="loading">添加任务项</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="footer">
      <p>© 2025 课程学习网站 | 数字化成长空间</p>
    </footer>
  </div>
</template>

<script>
import { subitemAPI, courseAPI } from '../api'
import { ElMessage } from 'element-plus'

export default {
  name: 'AddSubitemView',
  data() {
    return {
      activeIndex: 'add-subitem',
      subitemForm: {
        title: '',
        type: '',
        deadline: '', // 时间戳格式
        description: '',
        attachments: [] // 附件列表
      },
      subitemRules: {
        title: [
          { required: true, message: '请输入任务名称', trigger: 'blur' },
          { min: 2, max: 50, message: '任务名称长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择任务类型', trigger: 'change' }
        ],
        deadline: [
          { required: true, message: '请选择截止时间', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入任务描述', trigger: 'blur' },
          { min: 10, max: 1000, message: '任务描述长度在 10 到 1000 个字符', trigger: 'blur' }
        ]
      },
      courseInfo: null,
      loading: false,
      token: '',
      uploadUrl: import.meta.env.DEV ? '/api/demo/upload' : 'http://10.1.6.130:3000/api/demo/upload', // 上传API地址
      fileList: []
    }
  },
  computed: {
    userInfo() {
      const userInfoStr = localStorage.getItem('userInfo')
      return userInfoStr ? JSON.parse(userInfoStr) : null
    },
    courseId() {
      return this.$route.params.courseId
    }
  },
  async mounted() {
    // 获取用户信息
    this.token = localStorage.getItem('token')
    
    // 检查登录状态
    if (!this.token || !this.userInfo) {
      ElMessage.warning('请先登录')
      this.$router.push('/login')
      return
    }
    
    // 检查课程ID是否存在
    if (!this.courseId) {
      ElMessage.error('缺少课程ID参数')
      this.$router.push('/')
      return
    }
    
    // 加载课程信息
    await this.loadCourseInfo()
  },
  methods: {
    async loadCourseInfo() {
      try {
        const response = await courseAPI.getCourseById(this.courseId)
        if (response) {
          this.courseInfo = response
        } else {
          ElMessage.error('课程不存在')
          this.$router.push('/')
        }
      } catch (error) {
        console.error('加载课程信息错误:', error)
        ElMessage.error('加载课程信息失败，请稍后重试')
      }
    },
    async handleAddSubitem() {
      try {
        this.$refs.subitemForm.validate(async (valid) => {
          if (valid) {
            this.loading = true
            
            // 准备任务项数据，添加用户ID和课程ID
            const subitemData = {
              ...this.subitemForm,
              courseId: this.courseId,
              userId: this.userInfo.id, // 添加创建者ID
              createTime: Date.now(), // 添加创建时间戳
              status: '未完成' // 默认状态为未完成
            }
            
            // 调用API添加任务项
            const result = await subitemAPI.addCourseSubitem(subitemData)
            
            if (result && result.errno === 0) {
              ElMessage.success('任务项添加成功')
              
              // 提示用户是否继续添加
              this.$confirm('任务项添加成功，是否继续添加？', '提示', {
                confirmButtonText: '继续添加',
                cancelButtonText: '查看课程',
                type: 'success'
              }).then(() => {
                // 重置表单继续添加
                this.resetForm()
              }).catch(() => {
                // 跳转到课程详情页，并添加refresh参数
                this.$router.push({ path: `/course/${this.courseId}`, query: { refresh: 'true' } })
              })
            } else {
              ElMessage.error(result ? result.message || '任务项添加失败' : '任务项添加失败')
            }
          }
        })
      } catch (error) {
        console.error('添加任务项错误:', error)
        ElMessage.error('添加任务项失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    // 文件上传成功回调
    handleFileUpload(response, file, fileList) {
      if (response && response.url) {
        this.subitemForm.attachments.push(response.url)
        ElMessage.success('文件上传成功')
      } else {
        ElMessage.error('文件上传失败')
      }
    },
    // 移除上传的文件
    handleRemove(file, fileList) {
      const index = this.subitemForm.attachments.findIndex(attachment => attachment.includes(file.name))
      if (index > -1) {
        this.subitemForm.attachments.splice(index, 1)
      }
    },
    // 格式化日期时间
    formatDate(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },
    resetForm() {
      this.subitemForm = {
        title: '',
        type: '',
        deadline: '',
        description: '',
        attachments: []
      }
      this.fileList = []
      
      if (this.$refs.subitemForm) {
        this.$refs.subitemForm.resetFields()
      }
      
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles()
      }
    },
    handleCancel() {
      // 返回课程详情页
      this.$router.push(`/course/${this.courseId}`)
    }
  }
}
</script>

<style scoped>
.add-subitem-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}



/* 主内容区样式 */
.main-content {
  flex: 1;
  max-width: 1200px;
  width: 100%;
  margin: 20px auto;
  padding: 0 20px;
}

/* 添加任务项包装 */
.add-subitem-wrapper {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

/* 页面标题 */
.page-title {
  font-size: 24px;
  color: #303133;
  margin-bottom: 30px;
  text-align: center;
}

/* 课程信息卡片 */
.course-info-card {
  margin-bottom: 30px;
}

.card-header {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.course-info-content p {
  margin: 5px 0;
  color: #606266;
}

/* 任务项表单 */
.subitem-form {
  max-width: 800px;
  margin: 0 auto;
}

/* 文件上传样式 */
.upload-demo {
  margin-top: 10px;
}

/* 页脚 */
.footer {
  background-color: #fff;
  padding: 20px 0;
  text-align: center;
  border-top: 1px solid #e6e6e6;
  margin-top: auto;
}

.footer p {
  color: #909399;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .add-subitem-wrapper {
    padding: 20px;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .subitem-form {
    max-width: 100%;
  }
  
  .el-form {
    label-width: 100px !important;
  }
}
</style>